package com.freedom.rpc.thrift.registry;

import java.util.ArrayList;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.rpc.thrift.common.utils.LoggerUtils;
import com.freedom.rpc.thrift.server.utils.MyServerProperties;
import com.freedom.rpc.thrift.server.utils.TimeUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class HeartbeatRunnable implements Runnable {// 基于redis做心跳保活，每3秒钟发送一次publish消息

	private static final Logger logger = LogManager.getLogger(HeartbeatRunnable.class);

	@Override
	public void run() {
		LoggerUtils.info(logger, "heart beat runnable is running...");
		TimeUtils.sleepSeconds(6);// 这里是为了让Thrift server.serve方法执行完毕
		MyServerProperties property = MyServerProperties.getInstance();
		String ip = property.getIp();
		int port = property.getPort();
		//
		while (true) {
			//
			//
			//
			// 先上报心跳publish,尽最大努力!!!，主动心跳
			JedisPoolManager manager = JedisPoolManager.getInstance();
			ArrayList<JedisPool> pools = manager.getJedisPools();
			for (JedisPool pool : pools) {
				// 0)保证pool不为null
				if (null == pool) {
					continue;
				}
				//
				// 1)保证jedis不为null
				Jedis jedis = null;
				try {
					jedis = pool.getResource();
				} catch (Exception e) {
					LoggerUtils.error(logger, e.toString());
				}
				if (null == jedis) {
					continue;
				}
				//
				// 2)用jedis执行操作
				boolean error = false;
				try {
					jedis.publish(MyServerProperties.getInstance().getGlobalService(), ip + ":" + port);
				} catch (Exception e) {
					LoggerUtils.error(logger, e.toString());
					error = true;
				} finally {
					if (error) {
						pool.returnBrokenResource(jedis);
					} else {
						pool.returnResource(jedis);
					}
				}
				// 结束
			}

			//
			// 睡眠3秒->继续发送主动心跳heartbeat
			TimeUtils.sleepSeconds(3);
		}

	}

}
